package com.demo.house.controller;

import cn.hutool.core.util.ObjectUtil;
import com.demo.house.common.Result;
import com.demo.house.entity.User;
import com.demo.house.service.UserService;
import com.demo.house.vo.RequestVo.LoginVo;
import com.demo.house.vo.request.RequestMessageVo;
import com.demo.house.vo.request.RequestRegisteredVo;
import com.demo.house.vo.request.RequestUserVo;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author zhushubiao
 * @title: UserController
 * @projectName House
 * @description: TODO
 * @date 2021/3/16 14:41
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private HttpSession httpSession=null;
    @Autowired
    private UserService userService;
    @Autowired
    private Producer producer;


    /**
     * 查询
     *
     * @param id
     * @return
     */
    @GetMapping("getById/{id}")
    public Result getById(@PathVariable Integer id) {
        User byId = userService.getById(id);
        return Result.getSuccess().setData(byId);
    }


    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @GetMapping("deleteByid/{id}")
    public Result deleteByid(@PathVariable Integer id) {
        RequestUserVo vo = userService.deleteByid(id);
        return Result.getSuccess().setData(vo);
    }


    /**
     * 注册用户
     *
     * @param requestRegisteredVo
     * @return
     */
    @PostMapping("register")
    public Result register(@RequestBody RequestRegisteredVo requestRegisteredVo) {
        String captcha = (String) httpSession.getAttribute("captcha");
        if (captcha.equalsIgnoreCase(requestRegisteredVo.getUuid())) {
            User user = userService.getUsername(requestRegisteredVo.getUsername());
            if (!ObjectUtil.isEmpty(user)) {
                return Result.getFailure().setMsg("该账号已被注册");
            }
            return Result.getSuccess().setData(userService.register(requestRegisteredVo));
        }
        return Result.getFailure().setMsg("验证码错误");
    }


    //   用户登录
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        String captcha = (String) httpSession.getAttribute("captcha");
        System.out.println("yzm"+captcha);
        System.out.println("uuid"+loginVo.getUuid());
        if (captcha.equalsIgnoreCase(loginVo.getUuid())){
            User user = userService.login(loginVo);
            System.out.println(user);
            if (!ObjectUtil.isEmpty(user)) {
                if (user.getType() == 1) {
                    return Result.getSuccess().setMsg("房东登录成功").setData(user);
                }
                if (user.getType() == 2) {
                    return Result.getSuccess().setMsg("用户登录成功").setData(user);
                }
                return Result.getSuccess().setData(userService.login(loginVo));
            } else {
                return Result.getFailure().setMsg("账号或密码错误，请重新登入");
            }
        }
        return Result.getFailure().setMsg("验证码错误");
    }
    /**
     * 获取验证码
     * @param request
     * @param response
     * @throws IOException
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //禁用缓存
        response.setHeader("Cache-Control","no-store,no-cache");
        //设置返回的方式
        response.setContentType("image/jpeg");
        //生成验证码文本


        String captcha = producer.createText();
        System.out.println("验证码："+captcha);
        httpSession=request.getSession();

        httpSession.setAttribute(Constants.KAPTCHA_SESSION_KEY,captcha);
        httpSession.setAttribute("captcha",captcha);
        Object captcha1 = httpSession.getAttribute("captcha");
        System.out.println(captcha1);



        //设置过期时间
        httpSession.setMaxInactiveInterval(60);
        //得到验证码图片
        BufferedImage image = producer.createImage(captcha);

        //得到一个输出流
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
        IOUtils.closeQuietly(outputStream);
        try {
            outputStream.flush();
        }finally {
            outputStream.close();
        }
    }

    /**
     * 修改密码
     *
     * @param requestUserVo
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody RequestUserVo requestUserVo) {
        User user = userService.updateByid(requestUserVo);  //根据id查询
        if (!user.getPassword().equals(requestUserVo.getOldPassword())) {
            return Result.getFailure().setMsg("密码错误，请重试");
        }
        user.setPassword(requestUserVo.getNewPassword());
        userService.update(user);   //调修改方法
        return Result.getSuccess().setMsg("修改密码成功");
    }

    /**修改用户信息
     * @param user
     * @return
     */
    @PostMapping("updateVo")
    public Result update(@RequestBody User user) {
        User byId = userService.getById(user.getId());
        if (byId == null) {
            return Result.getFailure().setMsg("用户为空，不能修改");
        }
        return Result.getSuccess().setData(userService.updateByPrimaryKeySelective(user));
    }

    //查询用户姓名与电话号码
/*    @GetMapping("getMeesage/{id}")
    public Result get(@PathVariable Integer id){
        return Result.getSuccess().setData(userService.selectNameAndTelephone(id));
    }*/
}
